/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be trading_partnerful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
 * 02111-1307, USA.
 *
 * http://www.gnu.org/copyleft/gpl.html
 */

package l1j.server.server.clientpackets;
import java.util.logging.Level;
import java.util.logging.Logger;

import l1j.opqlo.Server.L1World.L1World;
import l1j.server.echo.ClientThread;
import l1j.server.server.model.L1Inventory;
import l1j.server.server.model.L1Trade;
import l1j.server.server.model.Instance.L1ItemInstance;
import l1j.server.server.model.Instance.L1NpcInstance;
import l1j.server.server.model.Instance.L1PcInstance;
import l1j.server.server.model.Instance.L1PetInstance;
import l1j.server.server.serverpackets.S_ServerMessage;
import l1j.server.server.model.item.L1ItemId;
//TODO 魔法娃娃使用判斷

/**
 * 處理收到由客戶端傳來增加交易物品的封包
 */
public class C_TradeAddItem extends ClientBasePacket {
	private static final String C_TRADE_ADD_ITEM = "[C] C_TradeAddItem";
	private static final Logger _log = Logger.getLogger(C_TradeAddItem.class.getName());
	@Override
	public String getType() {
		return C_TRADE_ADD_ITEM;
	}

	@Override
	public void start(final byte[] decrypt, final ClientThread client) {
		try {
			// 資料載入
			this.read(decrypt);

			final L1PcInstance pc = client.getActiveChar();
			if (pc == null) {
				return;
			}
			if (pc.isGhost()) { // 鬼魂模式
				return;
			}

			if (pc.isDead()) { // 死亡
				return;
			}

			if (pc.isTeleport()) { // 傳送中
				return;
			}

			// 物品OBJID
			final int itemObjid = this.readD();
			// 交易數量
			long itemcount = this.readD();
			//opqlo 防洗
			if (itemcount > Integer.MAX_VALUE) {
				itemcount = Integer.MAX_VALUE;
			}
			itemcount = Math.max(0, itemcount);
			//opqlo 防洗

			final L1ItemInstance item = pc.getInventory().getItem(itemObjid);
			if(item == null){
				return;
			}
			if (item.getCount() <= 0) {
				return;
			}

			//opqlo 防洗
			if(itemcount > 0 && itemcount < 2000000000
					&& item.getCount() > 0 && item.getCount() >= itemcount)
			{
				//opqlo 防洗
				final boolean isGM = pc.getAccessLevel() ==100 || pc.getAccessLevel() ==200;

				if (!isGM && !item.getItem().isTradable()) {//opqlo 修正GM可交易無法交易之道具
					pc.sendPackets(new S_ServerMessage(210, item.getItem().getName())); // \f1%0は捨てたりまたは他人に讓ることができません。
					return;
				}
				if (!isGM && !pc.getMap().isUsableItem()) {
					pc.sendPackets(new S_ServerMessage(563)); // \f1ここでは使えません。
					return;
				}
				if (item.getBless() >= 128) { // 封印された装備
					// \f1%0は捨てたりまたは他人に讓ることができません。
					pc.sendPackets(new S_ServerMessage(210, item.getItem().getName()));
					return;
				}
				if (item.getDeleteDate() != null) { //opqlo 道具天數刪除系統(無法交易)
					pc.sendPackets(new S_ServerMessage(210, item.getItem().getName()));
					return;
				}
				if (item.getItem().getItemId() == L1ItemId.ADENA && !item.isIdentified()) {
					pc.sendPackets(new S_ServerMessage(166,"金幣請先鑑定過後，再交易"));
					return;
				}
				for (final L1NpcInstance petNpc : pc.getPetList().values()) {
					if (petNpc instanceof L1PetInstance) {
						final L1PetInstance pet = (L1PetInstance) petNpc;
						if (item.getId() == pet.getItemObjId()) {
							// \f1%0は捨てたりまたは他人に讓ることができません。
							pc.sendPackets(new S_ServerMessage(210, item.getItem().getName()));
							return;
						}
					}
				}

				//TODO 魔法娃娃使用判斷
				/*for (final L1DollInstance doll : pc.getDollList().values()) {
					if (doll.getItemObjId() == item.getId()) {
						pc.sendPackets(new S_ServerMessage(1181));
						return;
					}
				}*/
				if(pc.getDollList().getDollByItem(item.getId()) !=null){
					pc.sendPackets(new S_ServerMessage(1181));
					return;
				}
				//TODO 魔法娃娃使用判斷

				final L1PcInstance tradingPartner = (L1PcInstance) L1World.getInstance().findObject(pc.getTradeID());
				if (tradingPartner == null) {
					return;
				}
				if (pc.getTradeOk()) {
					return;
				}
				if (tradingPartner.getInventory().checkAddItem(item, itemcount) != L1Inventory.OK) { // 容量重量確認及びメッセージ送信
					tradingPartner.sendPackets(new S_ServerMessage(270)); // \f1持っているものが重くて取引できません。
					pc.sendPackets(new S_ServerMessage(271)); // \f1相手が物を持ちすぎていて取引できません。
					return;
				}

				if (itemcount <= 0) {
					_log.info("要求增加交易物品傳回數量小於等於0: " + pc.getName());
					pc.getNetConnection().close();
					return;
				}

				final L1Trade trade = new L1Trade();
				trade.TradeAddItem(pc, item, itemcount);

				//opqlo 防洗
			}else{
				_log.info("[c]TradeAddItem 防洗踢除 "+client.getAccountName());
				client.close();
			}
			//opqlo 防洗
		} catch (final Exception e) {
			_log.log(Level.SEVERE, e.getLocalizedMessage(), e);

		} finally {
			this.over();
		}
	}
}
